<?php

namespace Kateba\AdminBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Yaml\Parser;
use Symfony\Component\Yaml\Dumper;

/**
 * Admin controller.
 */
class AdminController extends Controller {

    /**
     * site config action
     * @author ahmed
     */
    public function siteConfigAction() {
        $request = $this->getRequest();
        //create a new config
        $config = array();
        //get the container
        $container = $this->container;
        //set the configuration from the files
        $config['site_meta_title'] = $container->getParameter('site_meta_title');
        $config['site_meta_keywords'] = $container->getParameter('site_meta_keywords');
        $config['site_meta_description'] = $container->getParameter('site_meta_description');
        $config['admin_notifications_email'] = $container->getParameter('admin_notifications_email');
        $config['paypal_email'] = $container->getParameter('paypal_email');
        $config['site_telephone'] = $container->getParameter('site_telephone');
        $config['facebook_profile_link'] = $container->getParameter('facebook_profile_link');
        $config['twitter_profile_link'] = $container->getParameter('twitter_profile_link');
        $config['googleplus_profile_link'] = $container->getParameter('googleplus_profile_link');
        $config['linkedin_profile_link'] = $container->getParameter('linkedin_profile_link');

        $form = $this->createFormBuilder($config)
                ->add('site_meta_title', 'text')
                ->add('site_meta_keywords', 'text')
                ->add('site_meta_description', 'textarea')
                ->add('admin_notifications_email', 'email')
                ->add('paypal_email', 'email')
                ->add('site_telephone', null, array('required' => FALSE))
                ->add('facebook_profile_link', 'url', array('required' => FALSE))
                ->add('twitter_profile_link', 'url', array('required' => FALSE))
                ->add('googleplus_profile_link', 'url', array('required' => FALSE))
                ->add('linkedin_profile_link', 'url', array('required' => FALSE))
                ->getForm();

        //check if the form is posted
        if ($request->getMethod() == 'POST') {
            //bind the submitted data
            $form->bindRequest($request);
            //check that the form is valid
            if ($form->isValid()) {
                //form data array
                $formDataArray = $form->getData();
                //this is for checking if any error message occured
                $message = FALSE;
                //this flag is for opening the first configuration file
                $firstFileChange = FALSE;
                //check if any of the configurations in the first file need change
                if ($formDataArray['site_meta_title'] != $container->getParameter('site_meta_title')) {
                    $firstFileChange = TRUE;
                }
                if ($formDataArray['site_meta_keywords'] != $container->getParameter('site_meta_keywords')) {
                    $firstFileChange = TRUE;
                }
                if ($formDataArray['site_meta_description'] != $container->getParameter('site_meta_description')) {
                    $firstFileChange = TRUE;
                }
                if ($formDataArray['admin_notifications_email'] != $container->getParameter('admin_notifications_email')) {
                    $firstFileChange = TRUE;
                }
                if ($formDataArray['paypal_email'] != $container->getParameter('paypal_email')) {
                    $firstFileChange = TRUE;
                }
                if ($formDataArray['site_telephone'] != $container->getParameter('site_telephone')) {
                    $firstFileChange = TRUE;
                }
                if ($formDataArray['facebook_profile_link'] != $container->getParameter('facebook_profile_link')) {
                    $firstFileChange = TRUE;
                }
                if ($formDataArray['twitter_profile_link'] != $container->getParameter('twitter_profile_link')) {
                    $firstFileChange = TRUE;
                }
                if ($formDataArray['googleplus_profile_link'] != $container->getParameter('googleplus_profile_link')) {
                    $firstFileChange = TRUE;
                }
                if ($formDataArray['linkedin_profile_link'] != $container->getParameter('linkedin_profile_link')) {
                    $firstFileChange = TRUE;
                }


                //check if we need to open the first file to change it is config
                if ($firstFileChange) {
                    //the configuration file path
                    $configFile = __DIR__ . '/../../SiteBundle/Resources/config/services.yml';
                    //create a new yaml parser
                    $yaml = new Parser();
                    //try to open the configuration file
                    $content = @file_get_contents($configFile);
                    //check if we opened the file
                    if ($content !== FALSE) {
                        //file opened try to parse the content
                        try {
                            $value = $yaml->parse($content);
                        } catch (\Exception $e) {
                            // an error occurred during parsing
                            return $this->render('::general_admin.html.twig', array(
                                        'message' => 'Unable to parse the YAML File: ' . $configFile . '<br/><strong>Please fix this: </strong>' . $e->getMessage()
                                    ));
                        }
                        //set the parameters in the file
                        $value['parameters']['site_meta_title'] = $formDataArray['site_meta_title'];
                        $value['parameters']['site_meta_keywords'] = $formDataArray['site_meta_keywords'];
                        $value['parameters']['site_meta_description'] = $formDataArray['site_meta_description'];
                        $value['parameters']['admin_notifications_email'] = $formDataArray['admin_notifications_email'];
                        $value['parameters']['paypal_email'] = $formDataArray['paypal_email'];
                        $value['parameters']['site_telephone'] = $formDataArray['site_telephone'];
                        $value['parameters']['facebook_profile_link'] = $formDataArray['facebook_profile_link'];
                        $value['parameters']['twitter_profile_link'] = $formDataArray['twitter_profile_link'];
                        $value['parameters']['googleplus_profile_link'] = $formDataArray['googleplus_profile_link'];
                        $value['parameters']['linkedin_profile_link'] = $formDataArray['linkedin_profile_link'];

                        //prepare a dumper to dump our data in the file
                        $dumper = new Dumper();
                        $yaml = $dumper->dump($value, 3);
                        //write the data to the file
                        $writed = @file_put_contents($configFile, $yaml);
                        if ($writed === FALSE) {
                            //an error occurred during parsing
                            $message = "Unable to write in the YAML file: $configFile";
                        }
                    } else {
                        // an error occurred during parsing
                        $message = "Unable to open the YAML file: $configFile";
                    }
                }
                //get the session to set flag
                $session = $this->get('session');

                //clear the previous flashes
                $session->getFlashBag()->clear();
                //check if any error occured
                if ($message) {
                    //set the error flag
                    $session->getFlashBag()->set('error', $message);
                } else {
                    //check if user changed any thing in the form
                    if ($firstFileChange) {
                        //clear the cache for the new configurations to take effect
                        exec(PHP_BINDIR . '/php ' . __DIR__ . '/../../../../app/console cache:clear -e prod');
                        exec(PHP_BINDIR . '/php ' . __DIR__ . '/../../../../app/console cache:warmup --no-debug -e prod');
                        //set the success flag
                        $session->getFlashBag()->set('success', 'Your configurations were saved');
                        return $this->redirect($this->generateUrl('admin_site_config', array(), TRUE));
                    } else {
                        //set the notice flag
                        $session->getFlashBag()->set('notice', 'Nothing changed');
                    }
                }
            }
        }
        return $this->render('KatebaAdminBundle:Admin:siteSettings.html.twig', array(
                    'form' => $form->createView()
                ));
    }

    /**
     * @author Mahmoud
     */
    public function sitePagesAction() {
        $privacyArFilePath = __DIR__ . '/../../../../web/site-pages/privacy-ar.html';
        $privacyEnFilePath = __DIR__ . '/../../../../web/site-pages/privacy-en.html';
        
        $termsArFilePath = __DIR__ . '/../../../../web/site-pages/terms-ar.html';
        $termsEnFilePath = __DIR__ . '/../../../../web/site-pages/terms-en.html';
        
        $careerArFilePath = __DIR__ . '/../../../../web/site-pages/career-ar.html';
        $careerEnFilePath = __DIR__ . '/../../../../web/site-pages/career-en.html';
        
        $aboutArFilePath = __DIR__ . '/../../../../web/site-pages/about-ar.html';
        $aboutEnFilePath = __DIR__ . '/../../../../web/site-pages/about-en.html';
        
        $scholarshipsArFilePath = __DIR__ . '/../../../../web/site-pages/scholarships-ar.html';
        $scholarshipsEnFilePath = __DIR__ . '/../../../../web/site-pages/scholarships-en.html';
        
        $data = array();
        $data['aboutArText'] = file_get_contents($aboutArFilePath);
        $data['aboutEnText'] = file_get_contents($aboutEnFilePath);
        $data['scholarshipsArText'] = file_get_contents($scholarshipsArFilePath);
        $data['scholarshipsEnText'] = file_get_contents($scholarshipsEnFilePath);
        $data['careerArText'] = file_get_contents($careerArFilePath);
        $data['careerEnText'] = file_get_contents($careerEnFilePath);
        
        $data['privacyArText'] = file_get_contents($privacyArFilePath);
        $data['privacyEnText'] = file_get_contents($privacyEnFilePath);
        $data['termsArText'] = file_get_contents($termsArFilePath);
        $data['termsEnText'] = file_get_contents($termsEnFilePath);
        
        $form = $this->createFormBuilder($data)
                ->add('aboutArText', 'textarea', array('required' => false, 'attr' => array('class' => 'ckeditor', 'style' => 'width:100%;height:300px')))
                ->add('aboutEnText', 'textarea', array('required' => false, 'attr' => array('class' => 'ckeditor', 'style' => 'width:100%;height:300px')))
                ->add('scholarshipsArText', 'textarea', array('required' => false, 'attr' => array('class' => 'ckeditor', 'style' => 'width:100%;height:300px')))
                ->add('scholarshipsEnText', 'textarea', array('required' => false, 'attr' => array('class' => 'ckeditor', 'style' => 'width:100%;height:300px')))
                ->add('careerArText', 'textarea', array('required' => false, 'attr' => array('class' => 'ckeditor', 'style' => 'width:100%;height:300px')))
                ->add('careerEnText', 'textarea', array('required' => false, 'attr' => array('class' => 'ckeditor', 'style' => 'width:100%;height:300px')))
                ->add('privacyArText', 'textarea', array('required' => false, 'attr' => array('class' => 'ckeditor', 'style' => 'width:100%;height:300px')))
                ->add('privacyEnText', 'textarea', array('required' => false, 'attr' => array('class' => 'ckeditor', 'style' => 'width:100%;height:300px')))
                ->add('termsArText', 'textarea', array('required' => false, 'attr' => array('class' => 'ckeditor', 'style' => 'width:100%;height:300px')))
                ->add('termsEnText', 'textarea', array('required' => false, 'attr' => array('class' => 'ckeditor', 'style' => 'width:100%;height:300px')))
                ->getForm();
        $request = $this->getRequest();
        if ($request->getMethod() == 'POST') {
            $form->bindRequest($request);
            if ($form->isValid()) {
                $data = $form->getData();
                file_put_contents($aboutArFilePath, $data['aboutArText']);
                file_put_contents($aboutEnFilePath, $data['aboutEnText']);
                file_put_contents($scholarshipsArFilePath, $data['scholarshipsArText']);
                file_put_contents($scholarshipsEnFilePath, $data['scholarshipsEnText']);
                file_put_contents($careerArFilePath, $data['careerArText']);
                file_put_contents($careerEnFilePath, $data['careerEnText']);
                file_put_contents($privacyArFilePath, $data['privacyArText']);
                file_put_contents($privacyEnFilePath, $data['privacyEnText']);
                file_put_contents($termsArFilePath, $data['termsArText']);
                file_put_contents($termsEnFilePath, $data['termsEnText']);
            }
        }
        return $this->render('KatebaAdminBundle:Admin:sitePages.html.twig', array(
                    'form' => $form->createView()
                ));
    }

}
